package com.aaa.controller;

import com.aaa.entity.MyReturn;
import com.aaa.entity.PageSort;
import com.aaa.entity.User;
import com.aaa.service.UserService;
import com.aaa.util.MyTools;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：admin
 * @date ：Created in 2022/6/27 14:36
 * @description：
 * @modified By：
 */

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    MyReturn myReturn = new MyReturn();

    /**
     * 跳转到显示所有用户的页面
     *
     * @return String
     */
    @RequestMapping("toShowUserPage.do")
    public String toShowUserPage() {
        return "showUser";
    }


    /**
     * 分页查询所有用户
     *
     * @param pageSort
     * @return
     */
    @RequestMapping("findAllUserPage.do")
    @ResponseBody
    public MyReturn findAllUserPage(PageSort pageSort) {
        Page<User> page = userService.findAllPageByPlugin(pageSort);
        //获取总条数
        myReturn.setCount(page.getTotal());
        //获取数据
        myReturn.setData(page.getResult());
        MyTools.getSuccessResult(myReturn);
        return myReturn;
    }

    /**
     * 添加用户
     *
     * @param user 实体
     * @return MyReturn
     */
    @RequestMapping("saveUser.do")
    @ResponseBody
    public MyReturn saveUser(User user, Integer roleId) {

        //判断用户名是否重复
        String username = user.getUsername();
        User dbUser = userService.findUserByName(username);
        if (dbUser != null) {
            MyTools.getFailResult(myReturn);
            myReturn.setMsg("用户名重复");
        } else {
            //获取用户输入的密码
            String password = user.getPassword();
            //加密
            Map<String, String> passwordSaltMap = MyTools.makePasswordSalt(password);
            //获取加密后的密码和盐值
            String passwordNew = passwordSaltMap.get("passwordNew");
            String salt = passwordSaltMap.get("salt");

            //得到创建时间
            Date date = new Date();

            //将生成的新密码和盐值和创建时间重新存入user实体中
            user.setPassword(passwordNew);
            user.setSalt(salt);
            user.setCreateTime(date);

            //将实体存入数据库
            int insertNum = userService.saveUser(user);

            int setCharacterNum = userService.setCharacter(user.getUserId(), roleId);

            //将插入的结果返回到前端页面，json，<状态码，消息，数据>
            if (insertNum > 0 && setCharacterNum > 0) {
                MyTools.getSuccessResult(myReturn);
            } else {
                MyTools.getFailResult(myReturn);
            }
        }
        return myReturn;
    }

    /**
     * 将头像上传到阿里云，并返回路径
     *
     * @param file 传入文件
     * @return MyReturn
     */
    @RequestMapping("uploadAli.do")
    @ResponseBody
    public MyReturn uploadAli(MultipartFile file) {
        //获取原始文件名
        String filename = file.getOriginalFilename();

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tHkMzpJMdfvbSHMAQKS";
        String accessKeySecret = "CL69mCE7ZN1AmaXDr39mBwG3FCmK8V";

        // 填写Bucket名称，例如examplebucket。
        String bucketName = "gjctest01";

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //上传之后的文件名
        String objectName = UUID.randomUUID() + filename;

        //返回路径
        String filePath = "https://" + bucketName + "." + endpoint + "/" + objectName;
        //创建一个HashMap用来存放图片路径
        HashMap hashMap = new HashMap();
        hashMap.put("src", filePath);
        myReturn.setData(hashMap);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 原始文件
            byte[] bytes = file.getBytes();

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(bytes));

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            //上传字符串
            ossClient.putObject(putObjectRequest);


        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return myReturn;
    }

    /**
     * 删除用户
     *
     * @param userId 数组
     * @return MyReturn
     */
    @RequestMapping("deleteUserById.do")
    @ResponseBody
    public MyReturn deleteUserById(@RequestParam Integer[] userId) {
        int delNum = 0;
        for (Integer id : userId) {
            userService.deleteUserById(id);
            userService.deleteRoleByUserid(id);
            delNum++;
        }
        if (delNum == userId.length) {
            MyTools.getSuccessResult(myReturn);
        } else {
            MyTools.getFailResult(myReturn);
        }
        return myReturn;
    }

    /**
     * 修改用户信息
     *
     * @param user 实体
     * @return MyReturn
     */
    @RequestMapping("updateUser.do")
    @ResponseBody
    public MyReturn updateUser(User user) {
        System.out.println(user);
        User dbUserByName = userService.findUserByName(user.getUsername());
        System.out.println(user);
        User dbUserById = userService.findUserById(user.getUserId());
        String dbPassword = dbUserById.getPassword();

        String password = user.getPassword();

        if (!dbPassword.equals(password)) {
            user.setPassword(password);
            Map<String, String> passwordSaltMap = MyTools.makePasswordSalt(password);
            String passwordNew = passwordSaltMap.get("passwordNew");
            //将生成的新密码和盐值重新存入user实体中
            String salt = passwordSaltMap.get("salt");
            user.setPassword(passwordNew);
            user.setSalt(salt);
        }

        if (dbUserByName != null && !dbUserByName.getUserId().equals(dbUserById.getUserId())) {
            MyTools.getFailResult(myReturn);
            myReturn.setMsg("用户名重复");
        } else {
            //得到修改时间
            Date date = new Date();
            user.setUpdateTime(date);
            int updateNum = userService.updateUser(user);
            if (updateNum > 0) {
                MyTools.getSuccessResult(myReturn);
            } else {
                MyTools.getFailResult(myReturn);
            }
        }

        return myReturn;
    }


    /**
     * 重置密码
     * @param user
     * @return
     */
    @RequestMapping ("updatePwd.do")
    @ResponseBody
    public MyReturn updatePwd(User user){
        Map<String, String> passwordSalt = MyTools.makePasswordSalt(user.getPassword());
        user.setPassword(passwordSalt.get("password"));
        user.setSalt(passwordSalt.get("salt"));
        int num = userService.resetPwd(user);
        if (num > 0) {
            MyTools.getSuccessResult(myReturn);
        } else {
            MyTools.getFailResult(myReturn);
        }
        return myReturn;
    }

}
